package com.houxiurong.controller;

import com.alibaba.fastjson.JSON;
import com.houxiurong.cache.CacheManagerUtils;
import com.houxiurong.cache.RedisConstant;
import com.houxiurong.cache.RedisUtils;
import com.houxiurong.entity.User;
import com.houxiurong.service.UserService;
import com.houxiurong.utils.DateConversion;
import com.houxiurong.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by houxiurong on 2017/6/29.
 */
@RestController
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${user.name}")
    private String name;

    @Value("${userString}")
    private String userString;


    @Autowired
    private UserService userService;

    @RequestMapping(value = "getUser", method = RequestMethod.GET)
    public String getUesr() {
        return userString;
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public User login(@RequestParam("name") String name,
                      @RequestParam("sex") Integer sex,
                      @RequestParam("age") Integer age,
                      @RequestParam("birthday") String birthday) {

        logger.info("param->birthday:{}",birthday);
        Date birthday1 = DateConversion.parseDate(birthday, DateConversion.DEFAULT_DATE_TIME);
        User user = new User(name, age, sex, birthday1);
        User ret=userService.login(user);
        System.out.println("======获取请求入参:" + user.toString());
        System.out.println("======数据库保存结果:" + ret.toString());
        return user;
    }

    public User cacheUserById(String id) {
        String redisKey = CacheManagerUtils.cacheKey(RedisConstant.AUTHORIZER_INFO, id);
        User user = RedisUtils.get(redisKey, User.class);
        if (user != null) {
            System.out.println("[user != null]" + user);
            return user;
        }
        /**防止缓存穿透(60s 控制)*/
        if (CacheManagerUtils.penetrateSupervisor(RedisConstant.AUTHORIZER_INFO, id)) {
            user = userService.getUserById(Integer.parseInt(id));
            if (user != null) {
                System.out.println("CacheManagerUtils.cacheTimeout="+CacheManagerUtils.cacheTimeout());
                RedisUtils.put(redisKey, user, CacheManagerUtils.cacheTimeout());
                return user;
            }
            /**防止缓存穿透*/
            CacheManagerUtils.storePenetrateSupervisor(RedisConstant.AUTHORIZER_INFO, id);
        }
        return null;
    }

    @RequestMapping("findAll")
    public List<User> findAll(){

        return userService.findAll();
    }

    @RequestMapping(value = "findUserByName/{name}",method = {RequestMethod.GET})
    public User findUserByName(@PathVariable("name") String name) {
        return userService.findUserByName(name);
    }

    @RequestMapping(value = "/params", method= RequestMethod.GET)
    @ResponseBody
    public String getUserByParams(@RequestParam(value = "name", defaultValue = "houxiurong1") String name,
                                   @RequestParam(value = "page", defaultValue = "0") Integer page,
                                   @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<User> pages=userService.findByNameNot(name,pageable);
        Iterator<User> it=pages.iterator();
        logger.info("查询结果为:{}",JSON.toJSONString(pages));
        while(it.hasNext()){
            System.out.println("======name:"+((User)it.next()).getId());
        }
        return "success...login....";
    }
}
